<template>
  <view class="search-container">
    <wd-search v-model="keyword" placeholder="请输入商品关键词" @search="handleSearch" />
    <view v-if="historyList.length" class="history-section">
      <text class="history-title">搜索历史</text>
      <view class="history-list">
        <view class="history-item" v-for="item in historyList" :key="item" @click="searchFromHistory(item)">
          {{ item }}
        </view>
      </view>
      <button @click="clearHistory" class="clear-btn">清空历史</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const keyword = ref('')
const historyList = ref([])

onMounted(() => {
  historyList.value = uni.getStorageSync('searchHistory') || []
})

function handleSearch() {
  const val = keyword.value
  if (!val || typeof val !== 'string' || !val.trim()) return
  // 保存历史
  let history = uni.getStorageSync('searchHistory') || []
  history = history.filter(i => i !== val)
  history.unshift(val)
  if (history.length > 20) history = history.slice(0, 20)
  uni.setStorageSync('searchHistory', history)
  historyList.value = history
  // 跳转到搜索结果页
  uni.navigateTo({ url: `/pages/search_page/search_page?keyword=${encodeURIComponent(val)}` })
}

function searchFromHistory(val) {
  if (!val || typeof val !== 'string' || !val.trim()) return
  // 保存历史
  let history = uni.getStorageSync('searchHistory') || []
  history = history.filter(i => i !== val)
  history.unshift(val)
  if (history.length > 20) history = history.slice(0, 20)
  uni.setStorageSync('searchHistory', history)
  historyList.value = history
  // 跳转到搜索结果页
  uni.navigateTo({ url: `/pages/search_page/search_page?keyword=${encodeURIComponent(val)}` })
}

function clearHistory() {
  uni.removeStorageSync('searchHistory')
  historyList.value = []
}
</script>

<style scoped>
.search-container { padding: 30rpx; }
.history-section { margin-top: 40rpx; }
.history-title { font-size: 28rpx; color: #666; margin-bottom: 20rpx; display: block; }
.history-list { display: flex; flex-wrap: wrap; gap: 16rpx; }
.history-item { background: #f5f5f5; padding: 12rpx 24rpx; border-radius: 30rpx; color: #333; cursor: pointer; }
.clear-btn { margin-top: 20rpx; color: #999; background: none; border: none; }
</style>